﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections;
using System.Reflection;

namespace JsonContractResolverDemo;

public class IgnoreNullPropertyResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var jsonProperty = base.CreateProperty(member, memberSerialization);

        if (typeof(IEnumerable).IsAssignableFrom(jsonProperty.PropertyType) &&
            typeof(ICollection).IsAssignableFrom(jsonProperty.PropertyType))
        {
            jsonProperty.Converter = new NullJsonConverter();
        }

        return jsonProperty;
    }
}